<template>
  <div class="comment-list">
    <van-list v-model="loading" 
    :finished="finished" 
    finished-text="没有更多了"
    @load="onload">
    <van-cell v-for="(item, index) in list" 
    :key="index" :title="item.content"/>
  </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment.js'
export default {
  name: 'CommentList',
  props:{
    source:{
      type:[Number,String,Object],
      required:true
    }
  },
  data(){
    return{
      list:[],
      loading:false,
      finished:false
    }
  },
  methods:{
    async onload(){
      try{
        const { data } = await getComments({
          type:'a',
          source:this.source.toString(),
          offset:this.offset,
          limit: this.limit
        })
        // 2. 将数据添加到列表中
        const { results } = data.data
        this.list.push(...this.list,...results)
        // 3. 将 loading 设置为 false
        this.loading = false
        // 4. 判断是否还有数据
        if(results.length){
          this.offset = data.data.last_id
        }else{
          this.finished = true
        }
      }catch(err){
        this.error = true
      this.loading = false
      }
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(()=>{
        for(let i = 0; i<10;i++){
          this.list.push(this.list.length + 1)
        }
        //  加载状态结束
        this.loading = false
        // 数据全部加载完成
        if(this.list.length >= 40){
          this.finished = true
        }
      },1000)
    }
  }
}
</script>

<style lang="less" scoped>
</style>